# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2025-2025, The OpenROAD Authors

"""Wraps the contents of tcl scripts as a cc files.

The rules wrap the tcl scripts in a extern c character array.
"""

def _tcl_encode_sta_impl(ctx):
    """Generates a single C++ file from the provided srcs in a DefaultInfo.
    """
    outfile_name = ctx.attr.out if ctx.attr.out else ctx.attr.name + ".cc"
    output_file = ctx.actions.declare_file(outfile_name)

    args = ctx.actions.args()
    args.add(ctx.file._encode_script)
    args.add(output_file)
    args.add(ctx.attr.char_array_name)
    args.add_all(ctx.files.srcs)

    ctx.actions.run(
        outputs = [output_file],
        inputs = ctx.files.srcs,
        arguments = [args],
        tools = [ctx.executable._tclsh, ctx.file._encode_script],
        executable = ctx.executable._tclsh,
        env = {
            # FIXME why is this needed?
            "TCL_LIBRARY": ctx.executable._tclsh.path + ".runfiles/tk_tcl/library",
        },
    )
    return [DefaultInfo(files = depset([output_file]))]

tcl_encode_sta = rule(
    implementation = _tcl_encode_sta_impl,
    attrs = {
        "char_array_name": attr.string(
            doc = "The name of the extern string array value in the generated file.",
            mandatory = True,
        ),
        "out": attr.string(
            doc = "The name of the C++ source file generated by these rules.",
        ),
        "srcs": attr.label_list(
            allow_empty = False,
            allow_files = [".tcl"],
            doc = "Tcl files to be wrapped.",
        ),
        "_encode_script": attr.label(
            default = "//src/sta:etc/TclEncode.tcl",
            allow_single_file = True,
        ),
        "_tclsh": attr.label(
            default = "@tk_tcl//:tclsh",
            executable = True,
            cfg = "exec",
        ),
    },
)
